package com.mofang.ticketing.common.web.exception;

import com.mofang.ticketing.common.core.exception.BizException;
import com.mofang.ticketing.common.core.result.Result;
import com.mofang.ticketing.common.core.result.ResultCode;
import feign.FeignException;
import feign.codec.DecodeException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author LGC
 */
@RestControllerAdvice
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
@RequiredArgsConstructor
public class FeignExceptionHandler {
    /**
     * 拦截 FeignException 异常，Jackson 处理失败等情况会进入
     */
    @ExceptionHandler(FeignException.class)
    public Result<?> handleFeignException(FeignException e) {
        log.error("FeignException: ", e);
        return Result.failed("feign 远程调用异常");
    }

    /**
     * 拦截 DecodeException 异常，decoder 中抛出的自定义全局异常会进入此处
     */
    @ExceptionHandler(DecodeException.class)
    public Result<?> handleDecodeException(DecodeException e) {
        Throwable cause = e.getCause();
        if (cause instanceof BizException) {
            BizException bizException = (BizException) cause;
            // 上游符合全局响应包装约定的再次抛出即可
            return Result.failed(bizException.getCode(), bizException.getMessage());
        }
        log.error("DecodeException: ", e);
        return Result.failed("feign 远程调用异常");
    }
}
